//
//  TitleSelectView.m
//  B2C
//
//  Created by xiaowu on 2017/7/26.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "TitleSelectView.h"

static CGFloat itemCount = 6.0;
static NSInteger TitleButtonTag = 58194;
static CGFloat itemOffset = 15;

@interface TitleSelectView ()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *lineView;
@end

@implementation TitleSelectView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _titleArr = [NSArray array];
        
        [self addSubview:self.scrollView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _titleArr = [NSArray array];
        
        [self addSubview:self.scrollView];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
}

// 通用方法
- (void)setupWithTitleStrsArr:(NSArray <NSString *> *)arr withIndex:(NSInteger)index {
    [self.scrollView removeAllSubviews];
    [self.scrollView addSubview:self.lineView];
    
    self.titleArr = arr;
    
    CGFloat width = 0;
    CGFloat itemWidth = 0;
    CGFloat offsetWidth = 0;
    for (NSInteger i = 0; i < self.titleArr.count; i++) {
        NSString *titleStr = [self.titleArr safeObjectAtIndex:i];
        
        
        NSDictionary *attributes = @{NSFontAttributeName:TextNormalFont16};
        CGFloat length = [titleStr boundingRectWithSize:CGSizeMake(ScreenWidth, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        length = ceilf(length);
       
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(width, 0, length + itemOffset * 2, self.height);
        width += button.width;
        
        if (i <= index) {
            offsetWidth = width;
            itemWidth = button.width;
        }

        [button setTitle:titleStr forState:UIControlStateNormal];
        [button setTitleColor:[UIColor gray66Color] forState:UIControlStateNormal];
        button.titleLabel.font = TextNormalFont16;
        
        button.tag = TitleButtonTag + i;
        
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:button];
    }
    [self.scrollView bringSubviewToFront:self.lineView];
    self.scrollView.contentSize = CGSizeMake(width, self.height);
    [self setIndexWithStrsArr:self.titleArr withShowIndex:index];
    
}

/**
 *  @brief str show index
 */
- (void)setIndexWithStrsArr:(NSArray *)arr withShowIndex:(NSInteger)index {
    self.titleArr = arr;
    self.currentIndex = index;
    
    CGFloat width = 0;
    CGFloat itemWidth = 0;
    for (NSInteger i = 0; i < self.titleArr.count; i++) {
        NSString *titleStr = [self.titleArr safeObjectAtIndex:i];
        NSDictionary *attributes = @{NSFontAttributeName:TextNormalFont16};
        CGFloat length = [titleStr boundingRectWithSize:CGSizeMake(ScreenWidth, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        itemWidth = ceilf(length) + itemOffset * 2;
        width += itemWidth;
        if (i == index) {
            break;
        }
    }
    
    
    UIButton *button = [self.scrollView viewWithTag:TitleButtonTag + index];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.lineView.center = CGPointMake(width - itemWidth * 0.5, self.height - self.lineView.height * 0.5);
    [self animationForLine:button withAnimation:NO];
}

- (void)setToShowIndex:(NSInteger)index withAnimation:(BOOL)animation{
    self.currentIndex = index;
    
    for (UIView *view in self.scrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            button.titleLabel.font = TextNormalFont16;
            [button setTitleColor:[UIColor gray66Color] forState:UIControlStateNormal];
            if (button.tag == TitleButtonTag + index) {
                button.titleLabel.font = [UIFont boldSystemFontOfSize:16];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [self animationForLine:button withAnimation:animation];
            }
        }
    }
    
}

- (void)buttonClick:(UIButton *)sender {
    NSInteger index = sender.tag - TitleButtonTag;
    self.currentIndex = index;
    [self animationForLine:sender withAnimation:YES];
    
    for (UIView *view in self.scrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            button.titleLabel.font = TextNormalFont16;
            [button setTitleColor:[UIColor gray66Color] forState:UIControlStateNormal];
        }
    }
    sender.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    if (self.block) {
        self.block(index);
    }
}

- (void)animationForLine:(UIButton *)sender withAnimation:(BOOL)animation{
    
    CGFloat offset = sender.right - self.scrollView.contentOffset.x;
//    if ((offset >= (self.scrollView.width - 100) && (sender.mj_x != 0)) || ((offset >= 0) && (sender.mj_x == 0)) ) {
    if (offset >= (self.scrollView.width - 100) && (sender.mj_x != 0)) {
           
        if (animation) {
            [self.scrollView scrollRectToVisible:CGRectMake(self.scrollView.contentOffset.x + offset - self.scrollView.width + 100, 0, self.scrollView.width, self.scrollView.height) animated:YES];
        } else {
            [self.scrollView setMj_offsetX:self.scrollView.contentOffset.x + offset - self.scrollView.width + 100];
        }
    } else if (sender.mj_x == 0) {
        if (animation) {
            [self.scrollView scrollRectToVisible:CGRectMake(0, 0, self.scrollView.width, self.scrollView.height) animated:YES];
        } else {
            [self.scrollView setMj_offsetX:0];
        }
    }
//    else if ((offset >= 0) && (sender.mj_x == 0)) {
//        if (animation) {
//            [self.scrollView scrollRectToVisible:CGRectMake(0, 0, self.scrollView.width, self.scrollView.height) animated:YES];
//        } else {
//            [self.scrollView setMj_offsetX:0];
//        }
//    }
    
    
    CGFloat leftOffset = self.scrollView.contentOffset.x - sender.left;
    if (leftOffset >= -100 && (sender.mj_x != 0)) {
        if (animation) {
            [self.scrollView scrollRectToVisible:CGRectMake(self.scrollView.contentOffset.x - leftOffset - 100, 0, self.scrollView.width, self.scrollView.height) animated:YES];
        } else {
            [self.scrollView setMj_offsetX:self.scrollView.contentOffset.x - leftOffset - 100];
        }
    }
    
    if (animation) {
        __weak typeof(self) weakSelf = self;
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.lineView.center = CGPointMake(sender.centerX, weakSelf.lineView.centerY);
        } completion:^(BOOL finished) {
            
        }];
    } else {
        self.lineView.center = CGPointMake(sender.centerX, self.lineView.centerY);
    }
}

#pragma mark - getters
- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [UIView new];
        _lineView.backgroundColor = [UIColor yellowLineColor];
        _lineView.size = CGSizeMake(42, 2);
    }
    return _lineView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

@end
